package com.dl.mall.config.redis;

import com.dl.mall.entity.user.OrderInfo;
import com.dl.mall.service.user.OrderService;
import com.dl.mall.service.user.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import sun.rmi.runtime.Log;

import javax.annotation.Resource;
import java.util.List;

/**
 * redis处理过期订单
 * @author DL
 * @create 2022-04-28 10:47
 */
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Resource
    private OrderService orderService;
    @Resource
    private ProductService productService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        if(expiredKey.startsWith("order:")){
            // order:开头的key，进行处理
            String orderId = expiredKey.split(":")[1]; //去掉order:
            log.info("监听到订单id为 {} 的订单已过期，将恢复该订单占用的库存",orderId);
            // 订单过期，将该订单状态设置为2
            orderService.modifyOrderById(orderId, 2);
            // 恢复该订单占用的库存
            List<OrderInfo> orderInfoList = orderService.getOrderInfoListById(orderId);
            int recovery = productService.recoverySpecsStock(orderInfoList);
        }
    }
}

